// $Id: handler.c 100 2011-10-21 15:05:36Z cedric.shih@gmail.com $
/*
 * Copyright 2011 Cedric Shih (cedric dot shih at gmail dot com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "log.h"

#include "handler.h"

struct niohttp_handler *niohttp_handler_list_find(
		struct niohttp_handler_list *list, const char *pattern)
{
	struct niohttp_handler *handler;

	TAILQ_FOREACH(handler, list, entry) {
		if (!strcmp(pattern, handler->pattern)) {
			return handler;
		}
	}

	return NULL;
}

int niohttp_handler_list_add(struct niohttp_handler_list *list,
		const char *pattern, niohttp_handler_cb cb, void *cbarg)
{
	int rc;
	struct niohttp_handler *handler;

	if ((handler = niohttp_handler_list_find(list, pattern))) {
		niohttp_error("exists: %s", pattern);
		rc = EEXIST;
		goto finally;
	}

	if (!(handler = (struct niohttp_handler *)
			calloc(1, sizeof(*handler)))) {
		rc = errno ? errno : -1;
		niohttp_error("calloc: %s", strerror(rc));
		goto finally;
	}

	if (!(handler->pattern = strdup(pattern))) {
		rc = errno ? errno : -1;
		niohttp_error("strdup: %s", strerror(rc));
		free(handler);
		goto finally;
	}

	handler->len = strlen(handler->pattern);
	handler->cb = cb;
	handler->cbarg = cbarg;
	TAILQ_INSERT_TAIL(list, handler, entry);
	rc = 0;

finally:
	return rc;
}

void niohttp_handler_list_del(struct niohttp_handler_list *list,
		struct niohttp_handler *handler)
{
	TAILQ_REMOVE(list, handler, entry);

	if (handler->pattern) {
		free(handler->pattern);
	}

	free(handler);
}

void niohttp_handler_list_clear(struct niohttp_handler_list *list)
{
	struct niohttp_handler *handler;

	while ((handler = TAILQ_FIRST(list))) {
		niohttp_handler_list_del(list, handler);
	}
}
